import {defineStore} from 'pinia'
import router from "@/router/index.js";

const position = JSON.parse(sessionStorage.getItem('position'))
const userInfo = JSON.parse(sessionStorage.getItem('userInfo'))
const city = JSON.parse(sessionStorage.getItem('city'))
export const userStore = defineStore('user', {
    state: () => ({
        userInfo: userInfo || null,
        position: position || null,
        city: city || null,
        todos: [],
        filter: 'all',
        // type 会自动推断为 number
        nextId: 0,
        keepAliveInclude: initKeepAliveInclude(),

    }),
    getters: {
        finishedTodos(state) {
            // 自动完成! ✨
            return state.todos.filter((todo) => todo.isFinished)
        },
        unfinishedTodos(state) {
            return state.todos.filter((todo) => !todo.isFinished)
        },
        /**
         * @returns {{ text: string, id: number, isFinished: boolean }[]}
         */
        filteredTodos(state) {
            if (this.filter === 'finished') {
                // 自动调用其他 getter ✨
                return this.finishedTodos
            } else if (this.filter === 'unfinished') {
                return this.unfinishedTodos
            }
            return this.todos
        },
    },
    actions: {
        setUserAge(age) {
            this.userInfo.age = age
        },
        // 任何数量的参数，返回一个 Promise 或者不返回
        addTodo(text) {
            // 你可以直接改变状态
            this.todos.push({text, id: this.nextId++, isFinished: false})
        },
        setPosition(position) {
            this.position = position
        },
        setCity(city) {
            sessionStorage.setItem('city', JSON.stringify(city))
            this.city = city
        },
        setUserInfo(userInfo) {
            this.userInfo = userInfo
        },
        setKeepAliveInclude(keepAliveInclude) {
            this.keepAliveInclude = keepAliveInclude
        }
    },
})

const initKeepAliveInclude = () => {
    const list = []
    router.options.routes.forEach((item) => {
        if (item.meta?.keepAlive) {
            list.push(item.name)
        }
        item.children?.map((ite) => {
            if (ite.meta?.keepAlive) {
                list.push(ite.name)
            }
        })
    })
    console.log('initKeepAliveInclude list', list)
    return list
}


export const deleteRuteCache = (routeName) => {
    const user = userStore()
    user.keepAliveInclude.splice(user.keepAliveInclude.indexOf(routeName), 1)
}
export const addRouteCache = (routeName) => {
    const user = userStore()

    if (!user.keepAliveInclude.includes(routeName)) {
        user.keepAliveInclude.push(routeName)
    }
}